package com.zc.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.alibaba.fastjson.JSONObject;

/**
 * 获取实体类的共通模板
 * @author zc
 *
 */
public class servletUtils {
	/**
	 * 获取提交的表单数据,封装成JavaBean（需保证字段名与表单实例字段一致）
	 * @return
	 * @throws ServletException 
	 * @throws IOException 
	 */
	public static <T> T  getFormTable(HttpServletRequest request,Class<T> clas) throws IOException, ServletException{
		Collection<Part> parts = request.getParts();
		T t=servletUtils.parseParameter(clas, request);
		System.out.println(parts.size());
		if(parts!=null) {
			 for (Part part : parts) {
				 System.out.println(part);
		            if (part.getContentType() != null) {//待测试
		                //文件的input
		                printMsg(part,t,clas);
		            } else {
		                //普通input
		                String value = request.getParameter(part.getName());
		                System.out.println("name="+part.getName()+",value="+value);
		            }
		            System.out.println("-------------------");
		      }
		 }
		return t;
	}
	/**
	 * 打印每一个文件的信息
	 * @param part
	 * @throws IOException
	 */
    public static <T> void printMsg(Part part,T t,Class<T> clas) throws IOException {
        //name的名称
        String name = part.getName();
        //文件的输入流。自己存储到电脑上的哪个位置都可以。
        InputStream inputStream = part.getInputStream();
        //文件的大小
        long size = part.getSize();
        //请求头信息
        Collection<String> headers = part.getHeaderNames();
        //文件类型
        String contentType = part.getContentType();
        //文件名
    	String filename =UUID.randomUUID().toString()+"."+contentType.substring(contentType.lastIndexOf("/")+1);
        //获取文件头信息
        String disp = part.getHeader("content-disposition");
        System.out.println("\n---------------------------");
        System.out.println("得到一个文件");
        System.out.println("name="+name);
        System.out.println("inputStream="+inputStream);
        System.out.println("size="+size);
        System.out.println("headers="+headers);
        System.out.println("filename="+filename);
        System.out.println("contentType="+contentType);
        System.out.println("disp="+disp);
        if (filename != null && !"".equals(filename)) {
        	File file=new File("d:/img/");
    		if(file!=null&&!file.exists()) {
    			file.mkdirs();
    		}
            part.write("d:/img/"+filename);
            try {
				clas.getMethod("set"+name.substring(0,1).toUpperCase()+name.substring(1),String.class)
				.invoke(t,"./Myservlet?method=showImg&imgPath=d:/img/"+filename);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
        }
    }
    /**
     * 获取文件
     * @return 文件存储位置
     * @throws ServletException 
     * @throws IOException 
     */
    public static <T> List<String>  getFile(HttpServletRequest request) throws IOException, ServletException{
    	Collection<Part> parts = request.getParts();
    	List<String> r=new ArrayList<String>();//文件存储位置
    	if(parts!=null) {
    		for (Part part : parts) {
    			System.out.println(part);
    			if (part.getContentType() != null) {
    				//文件的input
    				printMsg(part,r);
    			} else {
    				//普通input
    				String value = request.getParameter(part.getName());
    				System.out.println("name="+part.getName()+",value="+value);
    			}
    			System.out.println("-------------------");
    		}
    	}
    	return r;
    }
    /**
     * 打印每一个文件的信息
     * @param part
     * @param r 
     * @throws IOException
     */
    public static <T> void printMsg(Part part, List<String> r) throws IOException {
    	//name的名称
    	String name = part.getName();
    	//文件的输入流。自己存储到电脑上的哪个位置都可以。
    	InputStream inputStream = part.getInputStream();
    	//文件的大小
    	long size = part.getSize();
    	//请求头信息
    	Collection<String> headers = part.getHeaderNames();
    	//文件类型
    	String contentType = part.getContentType();
    	//文件名
    	String filename =UUID.randomUUID().toString()+"."+contentType.substring(contentType.lastIndexOf("/")+1);
    	//获取文件头信息
    	String disp = part.getHeader("content-disposition");
    	System.out.println("\n---------------------------");
    	System.out.println("得到一个文件");
    	System.out.println("name="+name);
    	System.out.println("inputStream="+inputStream);
    	System.out.println("size="+size);
    	System.out.println("headers="+headers);
    	System.out.println("filenameUtiles="+filename);
    	System.out.println("contentType="+contentType);
    	System.out.println("disp="+disp);
    	if (filename != null && !"".equals(filename)) {
    		File file=new File("d:/img/");
    		if(file!=null&&!file.exists()) {
    			file.mkdirs();
    		}
    		part.write("d:/img/"+filename);
    		try {
    			// 数据库保存的图片路径
    			r.add("./Myservlet?method=showImg&imgPath=d:/img/"+filename);
    		} catch (Exception e) {
    			e.printStackTrace();
    		} 
    	}
    }
	/**
	 * 发送json信息到前端
	 * @param json
	 * @param response
	 * @throws IOException
	 */
	public static void print(JSONObject json,HttpServletResponse response) throws IOException {
		PrintWriter  pw=response.getWriter();
		pw.print(json);
		pw.flush();
		pw.close();
	}

	/**
	 *将参数自动解析到实体类中,需保证字段名与表单实例字段一致
	 * @param clas
	 * @param request
	 * @return
	 */
	public static <T> T parseParameter(Class<T> clas,HttpServletRequest request) {
		//1.获取参数
		Map<String,String[]> params=request.getParameterMap();
		//2.通过反射获取所有字段
		Field[] fields=clas.getDeclaredFields();
		T t=null;
		try {
			t=clas.newInstance();
			StringBuilder sdbValue=new StringBuilder();
			for(int i=0;i<fields.length;i++) {
				sdbValue.setLength(0);
				//3.通过字段名获取对应值
				String fieldName=fields[i].getName();
				String[] value=params.get(fieldName);
				if(value!=null&&value.length>0) {
					for(int j=0;j<value.length;j++) {
						sdbValue.append(value[j]);
						sdbValue.append(",");
					}
					sdbValue.setLength(sdbValue.length()-1);
				}
				//6.使用set方法设置值
				String methodName="set"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1);
				Method method=clas.getDeclaredMethod(methodName, fields[i].getType());
				method.invoke(t,parseType(fields[i].getType().getSimpleName(),
								sdbValue.length()>0?sdbValue.toString():null));
			}
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return t;
	}
	public   static Object parseType(String clasName,String value) {
		Object obj=null;
		switch(clasName) {
		case "int":
			obj=Integer.parseInt(value);
			break;
		case "Integer":
			if(value==null||"null".equals(value))
				obj=null;
			else
				obj=Integer.valueOf(value);
			break;
		case "Byte":
			obj = Byte.valueOf(value);
			break;
		case "byte":
			obj = Byte.parseByte(value);
			break;
		case "short":
			obj = Short.parseShort(value);
			break;
		case "Short":
			obj = Short.valueOf(value);
			break;
		case "long":
			obj = Long.parseLong(value);
			break;
		case "Long":
			obj = Long.valueOf(value);
			break;
		case "float":
			obj = Float.parseFloat(value);
			break;
		case "Float":
			obj = Float.valueOf(value);
			break;
		case "double":
			obj = Double.parseDouble(value);
			break;
		case "Double":
			if(value==null||"null".equals(value))
				obj=null;
			else
				obj = Double.valueOf(value);
			break;
		case "boolean":
			obj = Boolean.parseBoolean(value);
			break;
		case "Boolean":
			obj = Boolean.valueOf(value);
			break;
		default:
			obj=value;
			break;
		}
		return obj;
	}
}
